import { random } from '@wowon/utils';

// 权限 token : 登录 user
const loginUser = new Map();
// 刷新 token : 权限 token
const tokenMap = {};
// 存储定时器
const timer = {};
// (分钟) Token 过期时间
const TokenExpireTime = 20;
// (分钟) 刷新 Token 过期时间
const TokenRefreshExpireTime = 60 * 3;

/** 请求头类型 */
export const access_type = 'bearer';

/** 获取请求内的token */
export const getToken = (req) => (req.headers.authorization || '').replace(access_type + ' ', '');

/** 获取当前请求用户信息 */
export const getCurrentUser = (req) => {
  return loginUser.get(getToken(req));
};

/** 绑定token和用户信息 */
export const updateUser = (token, user) => {
  loginUser.set(token, user);
};

/** 删除token和用户绑定 */
export const removeUser = (token) => {
  loginUser.delete(token);
};

/** 获取刷新token */
export const signRefreshToken = () => {
  const refresh_token = 'rt-' + random(100000, 999999);
  timer[refresh_token] = setTimeout(() => {
    clearTimeout(timer[refresh_token + 'token']);
    const token = tokenMap[refresh_token];
    console.log('⎧refresh_token 过期：', token, refresh_token, tokenMap);
    if (!!token) removeUser(token);
    delete tokenMap[refresh_token];
    console.log('⎩refresh_token 过期：', tokenMap);
  }, 60000 * TokenRefreshExpireTime);
  return refresh_token;
};

const createToken = (refresh_token) => {
  if (!refresh_token) return '';
  const token = 't-' + random(100000, 999999);
  tokenMap[refresh_token] = token;
  return token;
};

/** 创建或获取新token */
export const signToken = (refresh_token, init) => {
  let token;
  if (init) {
    token = createToken(refresh_token);
  } else {
    token = tokenMap[refresh_token];
  }

  if (!token) return;

  clearTimeout(timer[refresh_token + 'token']);
  timer[refresh_token + 'token'] = setTimeout(() => {
    console.log('⎧token 过期：', token, refresh_token, tokenMap);
    const newToken = createToken(refresh_token);
    updateUser(newToken, loginUser.get(token));
    removeUser(token);
    console.log('⎩token 过期：', tokenMap);
  }, 60000 * TokenExpireTime);

  return token;
};
